﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using StackExchange.Redis;
using System;

namespace EasyIot.Common
{
    public class RedisCacheHelper
    {
        static ConnectionMultiplexer RedisConn { get; set; }
        static IServer RedisServer { get; set; }
        static IDatabase RedisDatabase { get; set; }

        public static void Init(string host, int port, string password, int dbindex, bool clear = false)
        {
            string strConnect = host + ":" + port + ",allowAdmin=true,password=" + password;
            RedisConn = ConnectionMultiplexer.Connect(strConnect);
            RedisServer = RedisConn.GetServer(host, port);
            RedisDatabase = RedisConn.GetDatabase(dbindex);
            //
            if (clear) FlushDatabase(dbindex);
        }

        static void FlushDatabase(int dbindex)
        {
            RedisServer.FlushDatabase(dbindex);
        }

        public static T Get<T>(string key)
        {
            RedisValue value = RedisDatabase.StringGet(key);

            if (!value.HasValue)
            {
                return default(T);
            }

            if (typeof(T) == typeof(string))
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            else
            {
                return Deserialize<T>(value);
            }
        }

        public static bool Set<T>(string key, T t)
        {
            if (typeof(T) == typeof(string))
            {
                return RedisDatabase.StringSet(key, t.ToString());
            }
            else
            {
                return RedisDatabase.StringSet(key, Serialize(t));
            }
        }

        static bool Remove(string key)
        {
            return RedisDatabase.KeyDelete(key);
        }

        static string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
        }

        static T Deserialize<T>(string input)
        {
            return JsonConvert.DeserializeObject<T>(input);
        }
    }
}
